<template>
  <div id="app">
    <div id="container">
    </div>
    <!--    安全图标-->
    <div class="HomeIndex" @click="toSecurity()">
      <van-image
          width="50px"
          height="50px"
          src="https://img95.699pic.com/element/40106/6770.png_860.png"
      />
    </div>
    <div class="mosaic">
      <div class="title">正在努力为您寻找司机<br>
        <div class="characters">请耐心等待</div>
      </div>
      <br>
      <div class="line_up">
        <div class="position">第1位</div>
        {{ sum }}人正在排队
      </div>
      <div class="waiting_time">
        <div class="position">约5分钟</div>
        已等待{{ formattedDuration }}分钟
      </div>
      <br>
      <div class="cancellation">
<!--        <button @click="sendWs">发送</button>-->
        <van-button round type="info" style="width: 100%" height="160px" @click="toIndex()">取消订单</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import dayjs from "dayjs"
import axios from "axios";


export default {
  data() {
    return {
      map: null,
      startTime: null,
      formattedDuration: '1',
      driverTime: null,
      driverLong: null,
      startaddress: "",
      endaddress: "",
      // 开始的经纬度
      startLatitudeAndLongitude: "",
      // 结束的经纬度
      endLatitudeAndLongitude: "",
      sum: 1,
      websocket:null,
      sendWsIntervalId: null,
      updateDurationIntervalId: null,
      //是否是自己取消的订单
      closeFlag: false,
      OrderInformation:{
        orderId:1,
        waitOrderTime: this.formattedDuration
      },
    };
  },
  mounted() {
    this.initAMap();
    this.startTime = dayjs();
    this.updateDuration();
    this.init();
    this.sendWsIntervalId = setInterval(this.sendWs, 3000);
    this.updateDurationIntervalId = setInterval(this.updateDuration, 1000 * 60);
  },
  unmounted() {
    this.map.destroy();
  },
  beforeDestroy() {
    clearInterval(this.sendWsIntervalId);
    clearInterval(this.updateDurationIntervalId);
  },
  created() {
    this.sta();
    this.CountSum();
    this.selectOrderById();
  },
  methods: {
    //获取页面的参数
    sta(){
      this.OrderInformation.orderId=this.$route.query.orderId;
      if (this.$route.query.flag){
        alert("司机已取消订单,已为您重新派发行程订单")
      }
    },
    //保存订单的等待时间
    saveOrderTime(){
      this.OrderInformation.waitOrderTime=this.formattedDuration;
      console.log(this.OrderInformation);
      axios.post("http://localhost:8081/wait/wait/saveOrderTime",this.OrderInformation).then(res=>{
        console.log(res);
      })
    },
    //通过订单获取开始的位置
    selectOrderById(){
      axios.post('http://localhost:8081/wait/wait/selectOrderById', this.OrderInformation).then(res=>{
        if (res.status === 200) {
          this.startLatitudeAndLongitude=res.data.data.startingPoint;
          this.endLatitudeAndLongitude=res.data.data.destination;
          // 获取起点和终点的经纬度
        }
      })
    },
    //取消订单跳转首页
    toIndex () {
      // 弹出选择框
      const confirmCancel = confirm('确定要取消订单吗？');
      if (confirmCancel) {
        axios.post('http://localhost:8081/wait/wait/closeOrderNoPeople', this.OrderInformation)
            .then(res => {
              console.log(res);
              if (res.status === 200) {
                this.closeFlag = true;
                console.log(1);
                this.$router.push({
                  path: '/'
                });
              } else {
                alert('服务器繁忙，暂时无法取消');
              }
            });
      }
    },
    toSecurity() {
      this.$router.push({
        path: '/security_center'
      })
    },
    //跳转司机已经接单页面，等待页面的跳转需要叫车页面传入orderId参数
    toReceive(){
      console.log(this.OrderInformation)
      this.$router.push({
        path: '/receive',
        query:{
          orderId:this.OrderInformation.orderId,
        }
      })
    },
    sendWs(){
      this.websocket.send(this.OrderInformation.orderId);
    },
    closeWS(){
      if (this.websocket){
        this.websocket.close();
      }
    },
    //websocket 进行连接
    init(){
      const self=this;
      let socketUrl="ws://localhost:8081/wait/api/websocket/1";
      this.websocket = new WebSocket(socketUrl);
      this.websocket.onopen=function (e){
        console.log(e)
        console.log("连接成功");
      }
      this.websocket.onclose=function (e){
        console.log(e);
        console.log("连接关闭");
      }
      this.websocket.onmessage=function (e){
        console.log(e.data);
        if (e.data=='轮到你了'){
          if (!self.closeFlag){
            self.saveOrderTime();
            self.toReceive();
            self.closeWS();
          }
        }
      }
    },
    CountSum() {
      axios.get("http://localhost:8081/wait/wait/waitPeople").then(res=>{
        this.sum = res.data.data;
        if (this.sum == 0) {
          this.sum = 1;
        } else {
          this.sum = res.data.data;
        }
      })
    },
    updateDuration() {
      if (this.startTime) {
        const endTime = dayjs();
        const durationInMilliseconds = endTime.diff(this.startTime, 'millisecond');
        const durationInMinutes = Math.floor(durationInMilliseconds / (1000 * 60));
        this.formattedDuration = `${durationInMinutes}`;
      }
      console.log(this.formattedDuration);
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9708bfa416d306b9dbaf55ea4e4a25f2",
      };
      let self = this;
      AMapLoader.load({
        key: "e6effe38515227141202b9fb6749424e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      }).then((AMap) => {
        var map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [116.397428, 39.90923],//地图显示中心点坐标
        });
        // 逆地址
        var geocoder = new AMap.Geocoder({
          city: "", //城市设为北京，默认：“全国”
        });
        AMap.plugin(
            ["AMap.ToolBar", "AMap.Driving", "AMap.Polyline", "AMap.Marker"],
            function () {
              //异步同时加载多个插件
              var toolbar = new AMap.ToolBar();
              map.addControl(toolbar);
              var driving = new AMap.Driving({
                map: map,
              }); //驾车路线规划
              // var在函数作用外,否则无法调用
              var startTranse = self.startLatitudeAndLongitude.split(",");
              var endTranse = self.endLatitudeAndLongitude.split(",");
              driving.search(
                  // 因地址值用2214.111的经纬度,所以需要格式转换
                  new AMap.LngLat(parseFloat(startTranse[0]), parseFloat(startTranse[1])),
                  new AMap.LngLat(parseFloat(endTranse[0]), parseFloat(endTranse[1])),
                  function (status, result) {
                    if (status === "complete") {
                      console.log("绘制驾车路线完成", result);
                      // 在这一块需要设置加时时间和大概的路程多少公里,用四舍五入的方式计算
                      self.driverTime = Math.round(result.routes[0].time / 60);
                      self.driverLong = Math.round(result.routes[0].distance / 1000);
                      // 逆地理编码获取地址信息
                      var start = self.startLatitudeAndLongitude.split(",");
                      var end = self.endLatitudeAndLongitude.split(",");
                      // 寻找开始地址的方法
                      geocoder.getAddress(start, function (status, result) {
                        if (status === 'complete' && result.regeocode) {
                          self.startaddress = result.regeocode.formattedAddress;
                        } else {
                          console.log("获取开始地址失败");
                        }
                      });
                      // 寻找结束地址的方法
                      geocoder.getAddress(end, function (status, result) {
                        if (status === 'complete' && result.regeocode) {
                          self.endaddress = result.regeocode.formattedAddress;
                          console.log(result.regeocode + "end");
                        } else {
                          console.log("获取结束地址失败");
                        }
                      });
                      console.log(start, end)
                      var text = new AMap.Text({
                        position: new AMap.LngLat(end[0], end[1]),
                        text: '距离为' + self.driverLong + '公里 大约' + self.driverTime + '分钟',
                        offset: new AMap.Pixel(-20, -20)
                      })
                      map.add(text);
                    } else {
                      console.log("获取驾车数据失败：" + result);
                    }
                  }
              );
            }
        );
      })
    },

  },
};
</script>
<style scoped>
#app {
  width: 100%;
  height: 800px;

  #container {
    width: 100%;
    height: 600px;
  }

  .mosaic {
    width: 100%;
    height: 200px;

    .title {
      font-size: 25px;
    }

    .characters {
      font-size: 20px;
    }

    .line_up {
      width: 50%;
      height: 60px;
      float: left;
      text-align: center;
    }

    .position {
      font-size: 30px;
    }

    .waiting_time {
      width: 50%;
      height: 60px;
      float: right;
      text-align: center;
    }

    .cancellation {
      float: left;
      width: 100%;
      height: 140px;
      margin-top: 20px;
    }
  }
}

</style>

